<?php

namespace app\common\model\coupon;

use app\common\model\Cart;
use app\common\model\goods\Goods;
use think\Model;


class Log extends Model
{





    // 表名
    protected $name = 'coupon_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'state_text'
    ];



    public function getTypeList()
    {
        return ['0' => __('Type 0'), '1' => __('Type 1'), '2' => __('Type 2')];
    }

    public function getStateList()
    {
        return ['0' => __('State 0'), '1' => __('State 1'), '2' => __('State 2')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function coupon()
    {
        return $this->belongsTo('app\common\model\coupon\Coupon', 'coupon_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public static function editState($user_id)
    {
        return  self::where('user_id', $user_id)->where('enddate', '<', date('Y-m-d'))->where('state', 1)->update(['state' => 0]) ? true : false;
    }
    //可使用优惠券列表
    public static function getUseCoupon($type, $pay_type = 'unused', $user_id)
    {
        $model = new self;
        if ($type == 1) {
            if ($pay_type == 'use') {
                $data = cache('order_' . $user_id);
                if (!$data) {
                    exception('请添加购买商品');
                }
                $goodsList = $data['goodsList'];

                $state = $goodsList['preferential'];
                if (!$state) {
                    $state = $goodsList['preferential'];
                }
                $model->where('money', '<', $data['deduction_money']);
            }
            $model->where('state', 1);
        } else {
            $model->whereIn('state', [0, 2]);
        }

        $list = $model->where('user_id', $user_id)->order('price desc')->paginate(10);

        if ($pay_type == 'use') {
            if ($state == '1') {
                $totalMoney = 0;

                if ($goodsList->preferential == '1') {
                    $totalMoney = $goodsList->totalMoney;
                }
            
                foreach ($list as $key => $vo) {

                    if ($vo->money > $totalMoney || $vo->startdate >= date('Y-m-d') || $vo->enddate <= date('Y-m-d')) {
                        unset($list[$key]);
                    }
                }
            } else {
                foreach ($list as $key => $vo) {
                    if ($vo->goods_type == '1') {
                        unset($list[$key]);
                    }
                }
            }
        }
        return $list;
    }
    //  下单默认使用最大面值优惠券
    public static function useMaxCoupon($money, $user_id)
    {
        return self::where('money', '<', $money)->where('user_id', $user_id)->where('state', 1)->where('startdate', '<', date('Y-m-d'))->where('enddate', '>', date('Y-m-d'))->order('price desc')->find();
    }
    //  检查优惠券是否能使用
    public static function useCoupon($money, $goods, $coupon_id, $user_id)
    {
        $coupon = self::get(['id' => $coupon_id, 'user_id' => $user_id]);
        $state = $goods['preferential'];
        if ($state!='1' && $coupon['goods_type'] == '1') {
            exception('非指定商品无法使用该优惠券');
        }
        if ($coupon['state'] == 0) {
            exception('优惠券已过期');
        }
        if ($coupon['state'] == 2) {
            exception('优惠券已使用');
        }
        if ($money <= $coupon['money']) {
            exception('优惠券最低使用金额￥' . $coupon['money']);
        }
        if ($coupon['enddate']) {
            if (date('Y-m-d') > $coupon['enddate']) {
                exception('有效截止日期：' . $coupon['enddate']);
            }
        }
        if (date('Y-m-d') < $coupon['startdate']) {
            exception('有效开始日期：' . $coupon['startdate']);
        }
        if ($money > $coupon['price']) {
            return $coupon['price'];
        } else {
            return $money;
        }
    }

    //  领券优惠券
    //  type：true  判断优惠券是否领取
    public static function getCoupon($coupon_id, $user_id, $type = true)
    {
        $coupon = Coupon::get($coupon_id);
        if (!$coupon) {
            exception('优惠券不存在');
        }
        $coupon = $coupon->toArray();
        $coupon['createtime'] = time();
        $coupon['user_id'] = $user_id;
        $coupon['coupon_id'] = $coupon['id'];
        if ($coupon['workrange']) {
            $workrange = explode(' - ', $coupon['workrange']);
            $coupon['startdate'] = $workrange[0];
            $coupon['enddate'] = $workrange[1];
        }
        $check = Log::where('user_id', $user_id)->where('coupon_id', $coupon_id)->count();
        if ($check && $type) {
            exception('【' . $coupon['name'] . '】优惠券已领取');
        }

        unset($coupon['id']);
        unset($coupon['workrange']);
        $couponLog = new Log();
        $res = $couponLog->allowField(true)->save($coupon);
    }
}
